import {
    CaretDownOutlined,
    ClearOutlined,
    LogoutOutlined,
    MessageOutlined,
    SafetyOutlined,
    UserOutlined,
} from '@ant-design/icons';
import {
    BetaSchemaForm,
    MenuDataItem,
    ProConfigProvider,
    ProLayout,
} from '@ant-design/pro-components';
import {
    Badge,
    ConfigProvider,
    Dropdown,
    Modal,
    Drawer
} from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useServerData } from '@sker/ui'
import { useWebSocket } from 'ahooks';
import { navigationTo, useAxiosWebGet, useChangePassword, useDrawer, useLocation } from '@sker/sdk';
import { createRoot } from 'react-dom/client';
import { useResizeDetector } from 'react-resize-detector'
import React from 'react'
import { Context, useAxiosWebPost, ILoginOptions, ICurrentUser, IMenu } from '@sker/sdk';
import { message as antdMessage, notification as antdNotification } from 'antd';
import { NavigationTo } from '@sker/sdk'
import { MineMessage } from './mine-message';
import { BrowserHistory, createBrowserHistory } from 'history'
import { SkerIcon } from './components/sker-icon'
import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';

export const AdminLayout: React.FC<React.PropsWithChildren<{}>> = ({ children }) => {
    const [serverData] = useServerData()
    const [Page, setPage] = useState<any>()
    const { width, height, ref } = useResizeDetector();
    const [currentUser, setCurrentUser] = useState<ICurrentUser>()
    const location = useLocation();
    const [props, setProps] = useServerData()
    const { latestMessage } = useWebSocket(`${location.protocol === 'http:' ? 'ws' : 'wss'}://${location.hostname}:${location.port}/web/admin?s=imeepos&m=core`);
    const { data: menuData, fetch: fetchMenu } = useAxiosWebGet('imeepos/core/menu/getMenu')
    const { fetch: clearCache } = useAxiosWebGet('imeepos/core/clearcache')
    const mainRef = useRef();
    const [lang, setLang] = useState<any>()
    useEffect(() => {
        setLang(zhCN)
    }, [])
    const changeLang = (lang: string)=>{
        if(lang === 'zh_CN'){
            setLang(zhCN)
        }else{
            setLang(enUS)
        }
    }
    const getHistory = () => {
        let adminHistory = Reflect.get(window, 'adminHistory')
        if (!adminHistory) {
            const history = createBrowserHistory()
            history.listen(async ({ location, action }) => {
                console.log({ location, action })
                const page = await navigationTo(location.pathname)
                if (page) {
                    setPage(page)
                }
            })
            Reflect.set(window, 'adminHistory', history)
        }
        return Reflect.get(window, 'adminHistory')
    }
    const [history, setHistory] = useState<BrowserHistory>(getHistory())
    const [url, setUrl] = useState<string>(location.pathname)
    useEffect(() => {
        setHistory(getHistory())
    }, [])
    const loadScript = async (link: string, params: any = {}, state: any = {}) => {
        if (!link) throw new Error(`link is ${link}`)
        const url = `/${link.split('/').filter(it => !!it).join('/')}`
        const query = Object.keys(params).map(k => `${k}=${params[k]}`).join('&')
        history.push(`${url}?${query}`, state)
        setUrl(url)
        const Page: any = await navigationTo(link)
        if (Page) {
            setPage(Page)
        }
    }
    const [navigate, setNavigate] = useState<NavigationTo>(() => loadScript)
    const { fetch: fetchMe } = useAxiosWebGet('imeepos/core/user/me')
    const { fetch: fetchLogin } = useAxiosWebPost('imeepos/core/user/login')
    const { fetch: fetchCaptch } = useAxiosWebGet('imeepos/core/user/captcha')
    const { fetch: fetchLogout } = useAxiosWebPost('imeepos/core/user/logout')
    const [message, contextMessage] = antdMessage.useMessage();
    const [notification, contextNotification] = antdNotification.useNotification()
    const [modal, contextModal] = Modal.useModal()
    const [fold, setFold] = useState<boolean>(false)
    const [menus, setMenus] = useState<IMenu[]>([])
    // 我的
    const me = async () => {
        try {
            const res = await fetchMe()
            if (res?.success) {
                setCurrentUser(res.data)
            } else {
                message.error(res.message)
                localStorage.setItem('refrence', window.location.href)
                window.location.href = serverData?.addon?.login_url || serverData?.login || '/imeepos/core/web/login'
            }
        } catch (e) {
            localStorage.setItem('refrence', window.location.href)
            window.location.href = serverData?.addon?.login_url || serverData?.login || '/imeepos/core/web/login'
        }
    }
    // 登录
    const login = async (options: ILoginOptions) => {
        const res = await fetchLogin(options)
        const { success, data } = res;
        if (success) {
            await message.success(res.message)
            const refrence = localStorage.getItem('refrence')
            localStorage.removeItem('refrence')
            localStorage.setItem('currentUser', JSON.stringify(res.data))
            window.location.href = refrence || data.welcome_link;
            return;
        } else {
            await message.error(res.message)
            return;
        }
    }
    const logout = async () => {
        const res = await fetchLogout()
        if (res.success) {
            await message.success(`已成功退出登录`)
            localStorage.removeItem('currentUser')
            window.location.href = serverData?.addon?.login_url || serverData?.login || '/imeepos/core/web/login'
            return;
        } else {
            await message.error(res.message)
            return;
        }
    }
    const getPageSetting = async () => { }
    /**
     * 验证码
     */
    const captcha = async (width: number, height: number) => {
        const { data, hashkey } = await fetchCaptch({ width: `${width}`, height: `${height}` })
        return { data, hashkey }
    }

    const { form, modal: changePasswordModal, setOpen } = useChangePassword()
    const getLogo = () => {
        const logo = props?.addon?.logo || props?.logo;
        if (logo) return <img src={logo} />
        return false;
    }
    const getTitle = () => {
        const title = props?.addon?.title || props?.title;
        return title ? title : false;
    }
    const changePassword = () => {
        setOpen(true)
    }
    const { props: mineMessageProps, setOpen: openMineMessage } = useDrawer('我的消息')
    useEffect(() => {
        if (mainRef.current) {
            const root = Reflect.get(window, 'REACT_ROOT')
            if (!root) {
                Reflect.set(window, 'NGER', true)
                Reflect.set(window, 'ROUTER_OUTLET', mainRef.current)
                Reflect.set(window, 'REACT_ROOT', createRoot(mainRef.current))
            }
        }
        me()
        fetchMenu().then(res => {
            setProps({
                ...res.theme
            });
        })
    }, [])
    useEffect(() => {
        if (!latestMessage?.data) return;
        const { type, payload } = JSON.parse(latestMessage.data)
        if (type === 'layout') {
            setProps(payload)
        }
    }, [latestMessage])
    return <div ref={ref}>
        {contextMessage}
        {contextNotification}
        {contextModal}
        <Context.Provider value={{
            width, height, login, getPageSetting, captcha,
            currentUser, setCurrentUser, me,
            menus, setMenus, fold, setFold, logout, message, notification, modal,
            navigate, setNavigate, history
        }}>
            <div
                id="admin-pro-layout"
                style={{
                    height: '100vh',
                    overflow: 'auto',
                }}
            >
                <Modal {...changePasswordModal}>
                    <BetaSchemaForm {...form} />
                </Modal>
                <Drawer {...mineMessageProps}>
                    <MineMessage />
                </Drawer>
                <ProConfigProvider hashed={false}>
                    <ConfigProvider
                        locale={lang}
                        getTargetContainer={() => {
                            return document.getElementById('admin-pro-layout') || document.body;
                        }}
                    >
                        <ProLayout
                            bgLayoutImgList={[]}
                            location={{
                                pathname: url,
                            }}
                            token={{
                                ...props?.token,
                            }}
                            siderMenuType="sub"
                            menu={{
                                collapsedShowGroupTitle: true,
                                type: 'group',
                                params: {
                                    menuData
                                },
                                request: async () => {
                                    const res = menuData;
                                    const token = res.theme.token;
                                    const items: MenuDataItem[] = [];
                                    res.menus.map((item: any) => {
                                        items.push({
                                            name: item.title,
                                            icon: <SkerIcon width={'20px'} height={'20px'} color={token?.sider?.colorTextMenu} fill={token?.sider?.colorTextMenu} name={item.icon} />,
                                            path: item.url,
                                            main: item.main,
                                            children: item.children.map((it: any) => {
                                                return {
                                                    name: it.title,
                                                    icon: <SkerIcon width={'20px'} height={'20px'} color={token?.sider?.colorTextMenu} fill={token?.sider?.colorTextMenu} name={it.icon} />,
                                                    path: it.url,
                                                    main: it.main,
                                                    children: it.children.map((it: any) => {
                                                        return {
                                                            name: it.title,
                                                            icon: <SkerIcon width={'20px'} height={'20px'} color={token?.sider?.colorTextMenu} fill={token?.sider?.colorTextMenu} name={it.icon} />,
                                                            path: it.url,
                                                            main: it.main,
                                                            children: it.children.map((it: any) => {
                                                                return {
                                                                    name: it.title,
                                                                    icon: <SkerIcon width={'20px'} height={'20px'} color={token?.sider?.colorTextMenu} fill={token?.sider?.colorTextMenu} name={it.icon} />,
                                                                    path: it.url,
                                                                    main: it.main,
                                                                    children: it.children.map((it: any) => {
                                                                        return {
                                                                            name: it.title,
                                                                            icon: <SkerIcon width={'20px'} height={'20px'} color={token?.sider?.colorTextMenu} fill={token?.sider?.colorTextMenu} name={it.icon} />,
                                                                            path: it.url,
                                                                            main: it.main,
                                                                        }
                                                                    })
                                                                }
                                                            })
                                                        }
                                                    })
                                                }
                                            })
                                        })
                                    })
                                    return items;
                                }
                            }}
                            avatarProps={{
                                src: 'https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg',
                                size: 'small',
                                title: <>{currentUser?.username}<CaretDownOutlined className='ml-6px' /></>,
                                render: (props, dom) => {
                                    return (
                                        <Dropdown
                                            menu={{
                                                items: [
                                                    {
                                                        key: 'mine',
                                                        icon: <UserOutlined />,
                                                        label: '个人中心',
                                                        onClick: () => {
                                                            navigate('imeepos/core/web/mine/profile')
                                                        }
                                                    },
                                                    {
                                                        key: 'change.password',
                                                        icon: <SafetyOutlined />,
                                                        label: '修改密码',
                                                        onClick: () => {
                                                            changePassword()
                                                        }
                                                    },
                                                    {
                                                        key: 'clear.cache',
                                                        icon: <ClearOutlined />,
                                                        label: '更新缓存',
                                                        onClick: () => {
                                                            clearCache().then(() => {
                                                                message.success(`清空缓存成功`)
                                                            })
                                                        }
                                                    },
                                                    { type: 'divider' },
                                                    {
                                                        key: 'logout',
                                                        danger: true,
                                                        icon: <LogoutOutlined />,
                                                        label: '退出登录',
                                                        onClick: () => logout()
                                                    },
                                                ],
                                            }}
                                        >
                                            {dom}
                                        </Dropdown>
                                    );
                                },
                            }}
                            actionsRender={(p) => {
                                if (p.isMobile) return [];
                                if (typeof window === 'undefined') return [];
                                return [
                                    <Badge key={'message'} count={props?.count}><MessageOutlined onClick={e => openMineMessage(true)} /></Badge>
                                ];
                            }}
                            logo={getLogo()}
                            title={getTitle()}
                            headerTitleRender={(logo, title, _) => {
                                const defaultDom = (
                                    <a>
                                        {logo}
                                        {title}
                                    </a>
                                );
                                if (typeof window === 'undefined') return defaultDom;
                                if (document.body.clientWidth < 1400) {
                                    return defaultDom;
                                }
                                if (_.isMobile) return logo;
                                return defaultDom
                            }}
                            onMenuHeaderClick={(e) => console.log(e)}
                            menuItemRender={(item, dom) => {
                                return (
                                    <div onClick={() => navigate(item.path)}>
                                        {dom}
                                    </div>
                                )
                            }}
                            {...props?.layout}
                        >
                            {Page && Page}
                            {!Page && <div id="app-container" ref={mainRef}>
                                {children}
                            </div>}
                        </ProLayout>
                    </ConfigProvider>
                </ProConfigProvider>
            </div>
        </Context.Provider>
    </div>;
}

